require 'roo'
class UploadController < ApplicationController
  def index
    @indices = Index.all
  end
  def show_out
    current_lists = Orderlist.where('index_id = ?', params[:id])
    @orderNos = current_lists.select(:fydh).distinct
    @lists = []
    weight = 0
    js = 0
    current_lists.each do |list|
      weight += list.zl
      js += list.js
    end
    @weight = weight
    @js = js
    @orderNos.each do |orderNo|
      @lists << current_lists.where('fydh = ?', orderNo.fydh.to_s)
    end
    index = Index.find(params[:id])
    index.update(:release_cont => index.release_cont + 1)
  end

  def show_release
    current_lists = Orderlist.where('index_id = ?', params[:id])
    @orderNos = current_lists.select(:fydh).distinct
    @lists = []
    weight = 0
    js = 0
    current_lists.each do |list|
      weight += list.zl
      js += list.js
    end
    @weight = weight
    @js = js
    @orderNos.each do |orderNo|
      @lists << current_lists.where('fydh = ?', orderNo.fydh.to_s)
    end
    index = Index.find(params[:id])
    index.update(:release_cont => index.release_cont + 1)
  end

  def show
    current_lists = Orderlist.where('index_id = ?', params[:id])
    @orderNos = current_lists.select(:fydh).distinct
    @lists = []
    @orderNos.each do |orderNo|
      @lists << current_lists.where('fydh = ?', orderNo.fydh.to_s)
    end
    index = Index.find(params[:id])
    index.update(:print_count => index.print_count + 1)
  end
  def upload
    @index = Index.new
    @index.count = 0
    @index.print_count = 0
    @index.release_cont = 0
    @index.out_count = 0
    upload_io = params[:excel]
    book = Roo::Spreadsheet.open(upload_io, extension: :xlsx)
    @index.excel = upload_io.original_filename
    @index.save
    sheet = book.sheet(0)
    sheet.each_with_index do |row, key|
      if key > 0
        zydh = row[0]
        fydh = row[1]
        jcrq = row[4]
        spbh = row[36]
        zwmc = row[37]
        ywmc = row[54]
        xs = row[35]
        gg = row[38]
        jg = row[41]
        js = row[20]
        ycd = row[28]
        sjr = row[26]
        sjrdz = row[54]
        sjrsfz = row[30]
        sjrdh = row[53]
        fjr = row[25]
        fjrdz = row[28]
        zl = row[50]
        Orderlist.create(zydh: zydh,fydh: fydh, jcrq: jcrq, spbh: spbh, zwmc: zwmc, ywmc: ywmc, xs: xs, gg: gg, jg: jg, js: js, ycd: ycd, sjr: sjr, sjrdz: sjrdz, sjrsfz: sjrsfz, sjrdh: sjrdh, fjr: fjr, fjrdz: fjrdz, zl: zl, index_id: @index.id )
        @index.count += 1
      end
    end
    @index.update(:count => @index.count)
    redirect_to :action => :index
  end

end
